package com.file.filedeal;

import com.file.filedeal.util.FileUtil;
import com.sun.istack.internal.NotNull;
import com.file.filedeal.entity.Grade;
import com.sun.xml.internal.fastinfoset.tools.XML_SAX_StAX_FI;
import lombok.extern.slf4j.Slf4j;
import com.file.filedeal.mapper.GradeMapper;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.io.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @author caoqianhuan
 * @date 2022/10/8
 * @Description:
 */
@RestController
@Slf4j
@Validated
public class FileController {

    @Autowired

    @Value("${uploadFile.basePath}")
    private String storeBaseUrl;

    @Resource
    private GradeMapper gradeMapper;

    @PostMapping("/uploadFile")
    public void uploadFile(@RequestParam("file") @NotNull MultipartFile file) {
        log.info("file origin name : {}", file.getOriginalFilename());
        String fileOriginName = file.getOriginalFilename();
        String fileType = FileUtil.getFileType(fileOriginName);
        log.info("fileType:{}", fileType);
        String storeFileUrl = storeBaseUrl + fileType + "\\";
        FileUtil.storeFile(file, storeFileUrl);
    }

    @PostMapping("/loadGrades")
    public void loadGrades(@RequestParam("file") MultipartFile file) {
        String type = FileUtil.getFileType(file.getOriginalFilename());
        if (!"xlsx".equals(type)) {
            return;
        }
        InputStream inputStream = null;
        try {
            inputStream = file.getResource().getInputStream();
            Workbook workbook = new XSSFWorkbook(inputStream);

            int sheetNum = workbook.getNumberOfSheets();
            List<Grade> gradeList = new ArrayList<>();
            for (int i = 0; i < sheetNum; i++) {
                Sheet sheet = workbook.getSheetAt(i);
                Iterator<Row> iterator = sheet.rowIterator();
                while (iterator.hasNext()) {
                    Grade grade = new Grade();
                    grade.setGrade( (int)iterator.next().getCell(0).getNumericCellValue());
                    gradeList.add(grade);
                }
                int rows = gradeMapper.insertBatch(gradeList);
            }

        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }


    @GetMapping("/downloadFile")
    public void downLoadFile(HttpServletResponse response) {
        //指定响应类型未未知的文件类型 以字节流响应 浏览器默认的处理方式是下载
        response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
        //配合响应头 指定为下附件形式下载
        response.setHeader("Content-Disposition", "attachment");
        //以内联在浏览器的方式展示 预览 也可下载
        //response.setHeader("Content-Disposition", "inline");
        byte[] bytes = new byte[1024];
        OutputStream outputStream = null;
        InputStream fileInputStream = null;
        try {
            outputStream = response.getOutputStream();
            fileInputStream = new BufferedInputStream(new FileInputStream("D:\\application\\filedeal\\pdf\\并发编程.pdf"));
            while (fileInputStream.read(bytes) > 0) {
                outputStream.write(bytes);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                outputStream.close();
                fileInputStream.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    @GetMapping("/test")
    public void test() {
        log.info("thread:{}", Thread.currentThread());
    }
}